<%--
  Created by IntelliJ IDEA.
  User: HUYUZHU
  Date: 2021/3/28
  Time: 13:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <c:import url="../template/_header.jsp"/>
    <title>系统管理-知了[团队知识管理应用]</title>
</head>

<body>
<div class="re-main">
    <c:import url="../template/_navbar.jsp"/>
    <div class="re-box-6 re-grey mt-85">
        <div class="container">
            <div class="row vertical-gap md-gap">
                <div class="col-lg-12">
                    <div class="re-box-decorated">
                        <div class="re-box-content">
                            <div class="re-form-group mnt-5 mb-9">
                                <a href="../manage">管理</a>&nbsp;|&nbsp;系统管理
                            </div>
                            <h2 class="h4 mnt-5 mb-9">系统管理</h2>
                            <div class="row" style="margin-top: 15px">
                                <div style="margin-left: 21px; width: 68%">
                                    <ul class="re-btn-manage re-btn-manage-style">
                                        <li style="margin: 10px -1px 0">
                                            <a href="#" style="height: 39px; border-radius: 0;"
                                               id="tab-es" class="re-btn-manage-cont" onclick="tabTo('es')">Elasticsearch</a>
                                        </li>
<%--                                        <li style="margin: 10px -1px 0">--%>
<%--                                            <a href="#" style="height: 39px; background-color: white; border-radius: 0;"--%>
<%--                                               id="tab-tika" class="re-btn-manage-cont" onclick="tabTo('tika')">Tika管理</a>--%>
<%--                                        </li>--%>
<%--                                        <li style="margin: 10px -1px 0">--%>
<%--                                            <a href="#" style="height: 39px; background-color: white; border-radius: 0;"--%>
<%--                                               id="tab-nfs" class="re-btn-manage-cont" onclick="tabTo('nfs')">NFS</a>--%>
<%--                                        </li>--%>
                                        <li style="margin: 10px -1px 0">
                                            <a href="#" style="height: 39px; background-color: white; border-radius: 0;"
                                               id="tab-mysql" class="re-btn-manage-cont" onclick="tabTo('mysql')">MySQL</a>
                                        </li>
                                        <li style="margin: 10px -1px 0">
                                            <a href="#" style="height: 39px; background-color: white; border-radius: 0;"
                                               id="tab-book" class="re-btn-manage-cont" onclick="tabTo('book')">应用配置</a>
                                        </li>
                                        <li style="margin: 10px -1px 0">
                                            <a href="#" style="height: 39px; background-color: white; border-radius: 0;"
                                               id="tab-openAPI" class="re-btn-manage-cont" onclick="tabTo('openAPI')">开放接口</a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div class="re-separator"></div>
                        <div class="re-form" id="manage-form">

                            <!-- START: ES Config Form -->
                            <div class="re-box-content" style="display: block" id="config-es">
                                <div class="re-form-group row">
                                    <div class="col-md-3 text-right pr-0">Elasticsearch服务地址：</div>
                                    <div class="col-md-9">
                                        <div id="es-addr">${es_addr}</div>
                                    </div>
                                </div>
                                <div class="re-form-group row mt-2">
                                    <div class="col-md-3 text-right pr-0">ES索引更新周期：</div>
                                    <div class="col-md-9">
                                        <div id="es-period">${es_period}&nbsp;s</div>
                                    </div>
                                </div>
                                <div class="re-form-group row mt-2">
                                    <div class="col-md-3 text-right pr-0">ES运行状态：</div>
                                    <div class="col-md-2">
                                        <div id="es-status" style="display: inline;">待生成</div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="checkEsStatus(true)">再次检测</button>

                                </div>
                                <%--        重新生成索引          --%>
                                <div class="re-form-group row mt-2">
                                    <div class="col-md-3 text-right pr-0">ES索引：</div>
                                    <div class="col-md-2">
                                        <div id="es-fresh" style="display: inline;">待生成</div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="checkEsFresh(true)">重新生成</button>
                                </div>
                            </div>
                            <!-- END: ES Config Form -->

                            <!-- START: Tika Config Form -->
<%--                            <div class="re-box-content" style="display: none" id="config-tika">--%>
<%--                                <div class="pull-right re-form-group">--%>
<%--                                    <button class="btn btn-primary" onclick="showEdit('tika')">修改</button>--%>
<%--                                </div>--%>
<%--                                <div class="re-form-group">--%>
<%--                                    <label for="tika-addr" class="mnt-7">Tika地址</label>--%>
<%--                                    <input type="text" class="form-control form-control-style-2 col-md-4" id="tika-addr"--%>
<%--                                           placeholder="请输入Tika地址"--%>
<%--                                           value="${tika_addr}" style="background-color: white" disabled="disabled">--%>
<%--                                </div>--%>
<%--                                <div class="re-form-group">--%>
<%--                                    <label for="tika-period" class="mnt-7">“未解析附件”检测周期（单位:秒）--%>
<%--                                        <button class="re-btn re-btn-sm btn-primary" style="margin-left: 20px"--%>
<%--                                                onclick="tikaDetection()">立即检测--%>
<%--                                        </button>--%>
<%--                                    </label>--%>
<%--                                    <input type="number" class="form-control form-control-style-2 col-md-4"--%>
<%--                                           id="tika-period" placeholder="请输入“未解析附件”检测周期"--%>
<%--                                           value="${tika_period}" style="background-color: white" disabled="disabled">--%>
<%--                                </div>--%>
<%--                                <div class="re-form-group">--%>
<%--                                    <label for="tika-retry" class="mnt-7">解析失败重试次数</label>--%>
<%--                                    <input type="number" class="form-control form-control-style-2 col-md-4"--%>
<%--                                           id="tika-retry" placeholder="请输入解析失败重试次数"--%>
<%--                                           value="${tika_retry}" style="background-color: white" disabled="disabled">--%>
<%--                                </div>--%>
<%--                            </div>--%>
                            <!-- END: Tika Config Form -->

                            <!-- START: NFS Config Form -->
                            <div class="re-box-content" style="display: none" id="config-nfs">
                                <div class="re-form-group row">
                                    <div class="col-md-3 text-right pr-0">NFS服务地址：</div>
                                    <div class="col-md-9">
                                        <div id="nfs-addr">${nfs_addr}</div>
                                    </div>
                                </div>
                            </div>
                            <!-- END: NFS Config Form -->

                            <!-- START: MySQL Config Form -->
                            <div class="re-box-content" style="display: none" id="config-mysql">
                                <div class="re-form-group row">
                                    <div class="col-md-3 text-right pr-0">MySQL地址：</div>
                                    <div class="col-md-9">
                                        <div id="mysql-addr">${mysql_addr}</div>
                                    </div>
                                </div>
                                <div class="re-form-group row mt-2">
                                    <div class="col-md-3 text-right pr-0">MySQL运行状态：</div>
                                    <div class="col-md-9">
                                        <div id="mysql-status" style="display: inline;"></div>
                                        <button class="re-btn re-btn-sm btn-primary" onclick="checkMysqlStatus(true)">再次检测</button>
                                    </div>
                                </div>
                            </div>
                            <!-- END: MySQL Config Form -->

                            <!-- START: BOOK Config Form -->
                            <div class="re-box-content" style="display: none" id="config-book">
                                <div class="re-form-group row">
                                    <div class="col-md-3 text-right pr-0">应用版本：</div>
                                    <div class="col-md-2">
                                        <div id="kms-version" style="display: inline;"></div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="checkKmsVersion(true)">刷新</button>
                                </div>
                                <div class="re-form-group row mt-2" id="book-label-area">
                                    <div class="col-md-3 text-right pr-0">“书籍”功能绑定标签ID：</div>
                                    <div class="col-md-2">
                                        <div id="book-label" style="display: inline;">${book_label}</div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="editBookLabel()">编辑</button>
                                </div>
                                <div class="re-form-group row mt-2" id="openapi-appkey-area">
                                    <div class="col-md-3 text-right pr-0">openApi-公开appKey：</div>
                                    <div class="col-md-2">
                                        <div id="openapi-appkey" style="display: inline;">${appKey_public}</div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="editAppKeyPublic()">编辑</button>
                                </div>
                                <div class="re-form-group row mt-2" id="default-password-area">
                                    <div class="col-md-3 text-right pr-0">用户默认密码：</div>
                                    <div class="col-md-2">
                                        <div id="default-password" style="display: inline;">${default_password}</div>
                                    </div>
                                    <button class="re-btn re-btn-sm btn-primary" onclick="editDefaultPassword()">编辑</button>
                                </div>
                            </div>
                            <!-- END: BOOK Config Form -->


                            <!-- START: OpenAPI Test Form -->
                            <div class="re-box-content" style="display: none" id="config-openAPI">
                                <div class="re-form-group row mt-2">
                                    <div for="test-config" class="col-md-3 col-form-label text-right pr-0">测试配置：</div>

                                    <div class="col-md-9">
                                        <textarea class="form-control" id="test-config" rows="5" cols="5000" style="border: 1px solid black !important; width: 70%; height: 100%;">${OpenAPI}</textarea>
                                    </div>
                                </div>

                                <div class="row mt-2 test-btn">
                                    <div class="col-md-3"></div>
                                    <div class="col-md-9 d-flex align-items-center">
                                        <button class="re-btn re-btn-sm btn-primary" onclick="startTest()">测试</button>
                                        <div style="margin-left: 344px;">
                                            <a href="#" class="text-decoration-underline text-dark" onclick="saveTestPlan()">保存当前测试方案</a>
                                        </div>
                                    </div>
                                </div>

                                <div  class="row" id="start-time-row" style="display: none;">
                                    <div class="col-md-3 text-right pr-0"></div>
                                    <div class="col-md-9">
                                        <label class="text-muted">测试开始时间：</label>
                                        <div id="test-start-time" style="display: inline;"><label class="text-muted">未开始</label></div>
                                    </div>
                                </div>
<%--                                <div class="row " id="test-result-row" style="display: none;">--%>
<%--                                    <div class="col-md-3 text-right pr-0"></div>--%>
<%--                                    <div class="col-md-9 d-flex align-items-center">--%>
<%--                                        <div style="width: 500px; overflow-wrap: break-word; word-break: break-all;">--%>
<%--                                            <label id="test-method" class="text-muted">search：</label>--%>
<%--                                        </div>--%>
<%--                                        <div  style="display: inline;">--%>
<%--                                            <label id="test-result" class="text-muted">未测试</label>--%>
<%--                                        </div>--%>
<%--                                    </div>--%>
<%--                                </div>--%>
                            </div>
                            <!-- END: BOOK Config Form -->

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!-- START: Footer -->
    <c:import url="../template/_footer.jsp"/>
    <!-- END: Footer -->
</div>
</body>
<!-- START: Scripts -->
<c:import url="../template/_include_js.jsp"/>
<script type="text/javascript">
    // init
    $(document).ready(function () {
        checkEsStatus(false);
        checkMysqlStatus(false);
        checkKmsVersion(false);
    });

    // switch page
    function tabTo(dest) {
        // tab bar
        $("a.re-btn-manage-cont").each(function () {
           $(this).css("background", "white");
        });
        $("#tab-" + dest).css("background", "");
        // form page
        $("#manage-form > div").each(function () {
            $(this).css("display", "none");
        });
        $("#config-" + dest).css("display", "block");

    }

    // es status
    function checkEsStatus(showTipBox) {
        $.ajax({
            type: "get",
            url: "/manage/esDelay?query=",
            success: function (data) {
                let str = '正常（' + data['time_delay'] + '）';
                $('#es-status').html(str);
                if (showTipBox) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '检测成功！'});
                }
            },
            error: function () {
                $('#es-status').html('异常');
                if (showTipBox) {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '检测失败！'});
                }
            }
        })
    }

    // es fresh
    function checkEsFresh(showTipBox) {
        $('#es-fresh').html("正在生成中");
        $.ajax({
            type: "get",
            url: "/esconfig/fresh",
            success: function (data) {
                // let str = '生成成功（' + data['time_delay'] + '）';
                let str = '成功'
                $('#es-fresh').html(str);
                if (showTipBox) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '更新成功！'});
                }
            },
            error: function () {
                $('#es-fresh').html('生成失败');
                if (showTipBox) {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '更新失败！'});
                }
            }
        })
    }

    // mysql status
    function checkMysqlStatus(showTipBox) {
        $.ajax({
            type: "get",
            url: "/manage/mysqlStatus",
            success: function (data) {
                let str = '正常（' + data['time_delay'] + '）';
                $('#mysql-status').html(str);
                if (showTipBox) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '检测成功！'});
                }
            },
            error: function () {
                $('#mysql-status').html('异常');
                if (showTipBox) {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '检测失败！'});
                }
            }
        })
    }

    // kms version
    function checkKmsVersion(showTipBox) {
        $.ajax({
            type: "get",
            url: "/manage/mysqlStatus",
            success: function (data) {
                $('#kms-version').html(data['kms_version']);
                if (showTipBox) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '刷新成功！'});
                }
            },
            error: function () {
                $('#kms-version').html('-');
                if (showTipBox) {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '刷新失败！'});
                }
            }
        })
    }

    // edit book label id
    function editBookLabel() {
        let nowId = $('#book-label').html();
        let htmlStr = "";
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">“书籍”功能绑定标签ID：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<input id=\"book-label-input\" class=\"form-control form-control-2\"></div>";
        htmlStr += "<button class=\"re-btn re-btn-sm\" onclick=\"submitBookLabel()\" style=\"background-color: #28a745\">保存</button>";
        $('#book-label-area').html(htmlStr);
        $('#book-label-input').val(nowId);
        $('#book-label-input').focus();
    }
    function submitBookLabel() {
        let book_label = $("#book-label-input").val();
        $.ajax({
            type: "post",
            url: "/manage/setBookConfig",
            data: {
                id: book_label
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
                    let htmlStr = '';
                    htmlStr += "<div class=\"col-md-3 text-right pr-0\">“书籍”功能绑定标签ID：</div>";
                    htmlStr += "<div class=\"col-md-2\">";
                    htmlStr += "<div id=\"book-label\" style=\"display: inline;\">" + book_label + "</div>";
                    htmlStr += "</div>";
                    htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editBookLabel()\">编辑</button>";
                    $('#book-label-area').html(htmlStr);
                    $('#book-label').html(book_label);
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！'});
            }
        })
    }

    // edit openapi public appkey
    function editAppKeyPublic() {
        let nowId = $('#openapi-appkey').html();
        let htmlStr = "";
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">openApi-公开appKey：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<input id=\"openapi-appkey-input\" class=\"form-control form-control-2\"></div>";
        htmlStr += "<button class=\"re-btn re-btn-sm\" onclick=\"submitAppKeyPublic()\" style=\"background-color: #28a745\">保存</button>";
        $('#openapi-appkey-area').html(htmlStr);
        $('#openapi-appkey-input').val(nowId);
        $('#openapi-appkey-input').focus();
    }
    function submitAppKeyPublic() {
        let appKey_public = $("#openapi-appkey-input").val();
        $.ajax({
            type: "post",
            url: "/manage/setAppKeyPublic",
            data: {
                appKey: appKey_public
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
                    let htmlStr = '';
                    htmlStr += "<div class=\"col-md-3 text-right pr-0\">openApi-公开appKey：</div>";
                    htmlStr += "<div class=\"col-md-2\">";
                    htmlStr += "<div id=\"openapi-appkey\" style=\"display: inline;\">" + appKey_public + "</div>";
                    htmlStr += "</div>";
                    htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editAppKeyPublic()\">编辑</button>";
                    $('#openapi-appkey-area').html(htmlStr);
                    $('#openapi-appkey').html(appKey_public);
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！'});
            }
        })
    }

    // edit default password
    function editDefaultPassword() {
        let default_password = $('#default-password').html();
        let htmlStr = "";
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">用户默认密码：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<input id=\"default-password-input\" class=\"form-control form-control-2\"></div>";
        htmlStr += "<button class=\"re-btn re-btn-sm\" onclick=\"submitDefaultPassword()\" style=\"background-color: #28a745\">保存</button>";
        $('#default-password-area').html(htmlStr);
        $('#default-password-input').val(default_password);
        $('#default-password-input').focus();
    }
    function submitDefaultPassword() {
        let default_password = $("#default-password-input").val();
        $.ajax({
            type: "post",
            url: "/manage/setDefaultPassword",
            data: {
                password: default_password
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
                    let htmlStr = '';
                    htmlStr += "<div class=\"col-md-3 text-right pr-0\">用户默认密码：</div>";
                    htmlStr += "<div class=\"col-md-2\">";
                    htmlStr += "<div id=\"default-password\" style=\"display: inline;\">" + default_password + "</div>";
                    htmlStr += "</div>";
                    htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editDefaultPassword()\">编辑</button>";
                    $('#default-password-area').html(htmlStr);
                    $('#default-password').html(default_password);
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！'});
            }
        })
    }

    //OpenAPI 测试
    // edit openapi appkey
    function editOpenApiAppKey() {
        let nowId = $('#openapi-test-appkey').html();
        let htmlStr = "";
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">appKey：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<input id=\"openapi-test-appkey-input\" class=\"form-control form-control-2\"></div>";
        htmlStr += "<button class=\"re-btn re-btn-sm\" onclick=\"submitAppKeyTest()\" style=\"background-color: #28a745\">保存</button>";
        $('#openapi-test-appkey-area').html(htmlStr);
        $('#openapi-test-appkey-input').val(nowId);
        $('#openapi-test-appkey-input').focus();
    }
    function submitAppKeyTest() {
        let appKey_public = $("#openapi-test-appkey-input").val();

        $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
        let htmlStr = '';
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">appKey：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<div id=\"openapi-test-appkey\" style=\"display: inline;\">" + appKey_public + "</div>";
        htmlStr += "</div>";
        htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editOpenApiAppKey()\">编辑</button>";
        $('#openapi-test-appkey-area').html(htmlStr);
        $('#openapi-test-appkey').html(appKey_public);
    }

    // edit label
    function editOpenApiBookLabel() {
        let default_label = $('#openapi-test-label').html();
        let htmlStr = "";
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">标签：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<input id=\"openapi-test-label-input\" class=\"form-control form-control-2\"></div>";
        htmlStr += "<button class=\"re-btn re-btn-sm\"  onclick=\"submitOpenAPILabelTest()\" style=\"background-color: #28a745\">保存</button>";
        $('#openapi-test-label-area').html(htmlStr);
        $('#openapi-test-label-input').val(default_label);
        $('#openapi-test-label-input').focus();
    }

    function submitOpenAPILabelTest() {
        let label_public = $("#openapi-test-label-input").val();

        $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
        let htmlStr = '';
        htmlStr += "<div class=\"col-md-3 text-right pr-0\">标签：</div>";
        htmlStr += "<div class=\"col-md-2\">";
        htmlStr += "<div id=\"openapi-test-label\" style=\"display: inline;\">" + label_public + "</div>";
        htmlStr += "</div>";
        htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editOpenApiBookLabel()\">编辑</button>";
        $('#openapi-test-label-area').html(htmlStr);
        $('#openapi-test-label').html(label_public);
    }


    function checkOpenAPIStatus() {
        $('#openapi-test-status').html("正在测试");
        let appkey = $("#openapi-test-appkey").html();
        let label = $("#openapi-test-label").html();

        // console.log("appkey 的值为：" + appkey);
        // console.log("label 的值为：" + label);
        $.ajax({
            type: "get",
            url: "/openapi/search",
            data: {
                appkey: appkey,
                pageNum:1,
                pageSize:1,
                queryStr:"",
                groupNames:"[]",
                labelNames:"['"+label+"']"
            },
            success: function (data) {

                $('#openapi-test-status').html(data['msg']);
                $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '测试成功！'});

            },
            error: function () {
                $('#openapi-test-status').html(data['msg']);
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '测试失败！'});
            }
        })
    }
    // show edit modal
    /* function showEdit(name) {
        $("#" + name + "-edit-modal").modal();
    } */

    // submit form
    /* function submitEsConfig() {
        let es_addr = $("#es-addr-edit").val();
        let es_edit = $("#es-period-edit").val();
        $.ajax({
            type: "post",
            url: "/manage/setEsConfig",
            data: {
                addr: es_addr,
                period: es_edit
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '提交成功！'});
                    $("#es-addr").val(es_addr);
                    $("#es-period").val(es_edit);
                    $("#es-edit-modal").modal("hide");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '提交异常！'});
            }
        })
    } */

    /* function submitTikaConfig() {
        let tika_addr = $("#tika-addr-edit").val();
        let tika_period = $("#tika-period-edit").val();
        let tika_retry = $("#tika-retry-edit").val();
        $.ajax({
            type: "post",
            url: "/manage/setTikaConfig",
            data: {
                addr: tika_addr,
                period: tika_period,
                retry: tika_retry
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '提交成功！'});
                    $("#tika-addr").val(tika_addr);
                    $("#tika-period").val(tika_period);
                    $("#tika-retry").val(tika_retry);
                    $("#tika-edit-modal").modal("hide");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '提交异常！'});
            }
        })
    } */

    /* function submitNfsConfig() {
        let nfs_addr = $("#nfs-addr-edit").val();
        $.ajax({
            type: "post",
            url: "/manage/setNfsConfig",
            data: {
                addr: nfs_addr
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '提交成功！'});
                    $("#nfs-addr").val(nfs_addr);
                    $("#nfs-edit-modal").modal("hide");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '提交异常！'});
            }
        })
    } */

    /* function submitBookConfig () {
        let book_label = $("#book-label-edit").val();
        $.ajax({
            type: "post",
            url: "/manage/setBookConfig",
            data: {
                id: book_label
            },
            success: function (data) {
                if (data["code"] == 200) {
                    $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '提交成功！'});
                    $("#book-label").val(book_label);
                    $("#book-edit-modal").modal("hide");
                } else {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '失败！' + data["msg"]});
                }
            },
            error: function () {
                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '提交异常！'});
            }
        })
    } */

    function saveTestPlan(){
        $.tipModal('confirm', 'warning', '确定保存测试方案？<br>（注意: 现存的测试方案将被覆盖! ）', function (result) {
            if (result == true) {

                let OpenAPI = $("#test-config").val();

                try {
                    var parsedContent = OpenAPI.replace(/\s/g, ' ');

                    parsedContent = parsedContent.replace(/:\s+/g, ':').replace(/,\s+/g, ',');

                    parsedContent = JSON.parse(parsedContent);
                }catch (e) {
                    $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败! json格式有误!'});
                    return;
                }

                $.ajax({
                    type: "post",
                    url: "/manage/setOpenAPI",
                    data: {
                        config: OpenAPI
                    },
                    success: function (data) {
                        if (data["code"] == 200) {
                            $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '修改成功！'});
                            // let htmlStr = '';
                            // htmlStr += "<div class=\"col-md-3 text-right pr-0\">用户默认密码：</div>";
                            // htmlStr += "<div class=\"col-md-2\">";
                            // htmlStr += "<div id=\"default-password\" style=\"display: inline;\">" + default_password + "</div>";
                            // htmlStr += "</div>";
                            // htmlStr += "<button class=\"re-btn re-btn-sm btn-primary\" onclick=\"editDefaultPassword()\">编辑</button>";
                            // $('#default-password-area').html(htmlStr);
                            $('#test-config').html(OpenAPI);
                        } else {
                            $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！' + data["msg"]});
                        }
                    },
                    error: function () {
                        $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '修改失败！'});
                    }
                })

            }
        });
    }

    //创建DIV布局
    function createTestDiv(method, methodIndex) {
        // 创建新的 div 元素
        var newDiv = document.createElement("div");
        newDiv.id = "test-result-row" + methodIndex;
        newDiv.className = "row";
        newDiv.style.display = 'none';

        var newDivCol = document.createElement("div");
        newDivCol.className = "col-md-3 text-right pr-0";
        newDiv.appendChild(newDivCol);

        var newDivCol2 = document.createElement("div");
        newDivCol2.className = "col-md-9 d-flex align-items-center";
        newDiv.appendChild(newDivCol2);

        var newDivWrap = document.createElement("div");
        newDivWrap.style = "width: 500px; overflow-wrap: break-word; word-break: break-all;";
        newDivWrap.id = "test-method" + methodIndex;
        newDivCol2.appendChild(newDivWrap);

        // 创建新的 label 元素用于显示方法名称
        // var newLabelMethod = document.createElement("label");
        // newLabelMethod.id = "test-method" + methodIndex;
        // newLabelMethod.className = "text-muted";
        // newLabelMethod.textContent = method + "：";
        // newDivWrap.appendChild(newLabelMethod);

        var newDivInline = document.createElement("div");
        newDivInline.style.display = "inline";
        newDivInline.id = "test-result" + methodIndex;
        newDivCol2.appendChild(newDivInline);

        // // 创建新的 label 元素用于显示测试结果
        // var newLabelResult = document.createElement("label");
        // newLabelResult.id = "test-result" + methodIndex;
        // newLabelResult.className = "text-muted";
        // newLabelResult.textContent = "未测试";
        // newDivInline.appendChild(newLabelResult);

        // 获取指定的 div 元素
        var targetDiv = document.getElementById("config-openAPI");

        // 将新的 div 元素插入到指定的 div 元素中
        targetDiv.appendChild(newDiv);

    }

    function verifyMethodIndex() {

        // console.log("共多少个测试方法", methodNum)

        for(var index = 0; index < methodNum; index++){

            // console.log("index索引", index)
            document.getElementById('test-result-row'+index).style.display = 'none';

        }
    }


    var methodNum = 0;
    function startTest() {

        if(methodNum != 0){
            for (var index = 0; index < methodNum; index++){
                document.getElementById('test-result-row'+index).style.display = 'none';
            }
        }

        // 获取当前的时间
        var now = new Date();
        // 将时间格式化为你想要的格式
        var timeString = now.getFullYear() + "-" + (now.getMonth() + 1).toString().padStart(2, '0') + "-"
            + now.getDate().toString().padStart(2, '0') + " " + now.getHours().toString().padStart(2, '0')
            + ":" + now.getMinutes().toString().padStart(2, '0');

        // 获取显示时间的元素
        var timeElement = document.getElementById("test-start-time");
        // 更新元素的内容
        timeElement.innerHTML = '<label class="text-muted">' + timeString + '</label>';

        // 显示开始时间和测试结果
        document.getElementById('start-time-row').style.display = 'flex';
        // document.getElementById('test-result-row').style.display = 'flex';

        // 获取textarea的内容
        var textareaContent = document.getElementById('test-config').value;

        // 替换所有的特殊空格字符为标准的空格字符
        textareaContent = textareaContent.replace(/\s/g, ' ');

        // 删除所有在冒号或逗号后面的空格
        textareaContent = textareaContent.replace(/:\s+/g, ':').replace(/,\s+/g, ',');

        // 将textarea的内容解析为JSON对象
        try {
            var parsedContent = JSON.parse(textareaContent);
        }catch (e) {
            verifyMethodIndex();

            $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: 'json格式有误!'});
            return;
        }


        // 创建一个空对象用于存储请求的数据
        var requestData = {};

        var methodIndex = 0;
        methodNum = 0;
        // 遍历每一个一级节点（接口）
        for (var method in parsedContent) {

            // 创建一个空对象用于存储每个接口的参数
            requestData[method] = {};

            // 遍历每一个二级节点（参数）
            for (var parameter in parsedContent[method]) {
                // 存储参数和值
                requestData[method][parameter] = parsedContent[method][parameter];
            }

            createTestDiv(method, methodIndex);

            document.getElementById('test-method' + methodIndex).innerHTML = '';
            document.getElementById('test-result' + methodIndex).innerHTML = '';

            methodIndex++;
            methodNum++;

        }
        // console.log(requestData)

        // 遍历每一个一级节点（接口）
        var methodIndex = 0;
        for (var method in requestData) {

            document.getElementById('test-result-row'+methodIndex).style.display = 'flex';

            // 使用立即执行的函数表达式来创建一个新的作用域
            (function(method, methodIndex) {
                // 延时 methodIndex * 1000 毫秒后执行这个函数
                setTimeout(function() {
                    // 获取该接口的所有参数
                    // console.log("方法：", method)
                    var params = requestData[method];

                    // search
                    if (method === 'search') {
                        var label = params['label'] !== undefined ? params['label'] : '';
                        var appkey = params['appkey'] !== undefined ? params['appkey'] : '';
                        var queryStr = params['queryStr'] !== undefined ? params['queryStr'] : '';

                        // console.log("search:",label,appkey,queryStr)

                        document.getElementById('test-method'+ methodIndex).innerHTML = '<label id="test-method" class="text-muted">' + 'search?appkey=' + appkey + '&&label=' + label + '&&queryStr=' + queryStr + '</label>';
                        document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[正在测试search]</label>';

                        // 检查是否所有必要的参数都已配置
                        if (!params['label'] && !params['appkey']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[label参数未配置,appkey参数未配置]</label>';
                            return;
                        }
                        if (!params['label']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[label参数未配置]</label>';
                            return;
                        }
                        if (!params['appkey']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[appkey参数未配置]</label>';
                            return;
                        }
                        // if (!requestData['queryStr']) {
                        //     document.getElementById('test-result').innerHTML = '<label style="color:black;">[queryStr参数未配置]</label>';
                        //     return;
                        // }

                        // 发送请求
                        $.ajax({
                            type: "get",
                            data: {
                                appkey: appkey,
                                pageNum: 1,
                                pageSize: 1,
                                queryStr: queryStr,
                                groupNames: "[]",
                                labelNames: "['" + label + "']"
                            },
                            url: "/openapi/search",
                            // data: requestData,
                            success: function (data) {
                                // 检查返回的数据是否符合预期
                                if (data['msg'] === '测试通过') {
                                    document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:green;">[' + data['msg'] +']</label>';
                                } else {
                                    document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:red;">[测试不通过(验参失败)]</label>';
                                }
                                $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '测试成功！'});

                            },
                            error: function () {
                                document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:red;">[测试不通过]</label>';
                                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '测试失败！'});
                            }
                        });
                    }
                    // detail
                    else if (method === 'detail') {

                        var id = params['id'] !== undefined ? params['id'] : '';
                        var appkey = params['appkey'] !== undefined ? params['appkey'] : '';

                        // console.log("detail:", id,appkey)
                        document.getElementById('test-method'+ methodIndex).innerHTML = '<label id="test-method" class="text-muted">' + 'datail?appkey=' + appkey + '&&id=' + id + '</label>';
                        document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[正在测试detail]</label>';

                        if (isNaN(id)) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[id参数应为数字格式]</label>';
                            return;
                        }
                        // 检查是否所有必要的参数都已配置
                        if (!params['id'] && !params['appkey']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[id参数未配置,appkey参数未配置]</label>';
                            return;
                        }
                        if (!params['id']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[id参数未配置]</label>';
                            return;
                        }
                        if (!params['appkey']) {
                            document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;">[appkey参数未配置]</label>';
                            return;
                        }

                        // 发送请求
                        $.ajax({
                            type: "get",
                            data: {
                                appkey: appkey,
                                id: id,
                            },
                            url: "/openapi/detail",
                            success: function (data) {

                                if (data['msg'] === '测试通过') {
                                    document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:green;">[' + data['msg'] +']</label>';
                                } else {
                                    document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:red;">[测试不通过(验参失败)]</label>';
                                }

                                $.fillTipBox({type: 'success', icon: 'glyphicon-alert', content: '测试成功！'});

                            },
                            error: function () {
                                document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:red;">[测试不通过]</label>';
                                $.fillTipBox({type: 'danger', icon: 'glyphicon-alert', content: '测试失败！'});
                            }
                        });
                    }
                    else{
                        document.getElementById('test-method'+ methodIndex).innerHTML = '<label id="test-method" style="color:red;">没有提供正确的测试的API接口名称(search/detail)</label>';
                        document.getElementById('test-result'+ methodIndex).innerHTML = '<label id="test-result" style="color:black;"></label>';

                    }
                }, methodIndex * 3000);  // 这里的 1000 是延时的毫秒数
            })(method, methodIndex);

            methodIndex++;

        }

    }




</script>
<style>
    .re-btn{
        border-radius: 3px;
    }
    .test-btn{
        margin-bottom: 10px;
    }
</style>
<!-- END: Scripts -->
</html>

